package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.MessageVipReq;
import com.ydkj.a37e_mall.Classes.Model.Response.MessageVipResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by hong on 2016/3/26.
 * <p/>
 * 会员消息
 */
public class MessageVip extends BaseActivity implements View.OnClickListener {

    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private ImageView img_back;
    private TextView tv_edit, tv_delete, tv_no_message_data;
    private PullToRefreshListView plv_message;

    private List<MessageVipResp.ResultEntity.DataEntity> dataEntityList;
    private List<Integer> delete_idList;
    private MessageVipAdapter messageVipAdapter;
    private static final int LOAD = 0;// 加载
    private static final int REFRESH = 1;//刷新
    private static final int MORE = 2;// 更多
    private String secret;
    private int page;
    private boolean is_edit = false;
    private int login_flag = 0;


    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_system);
        init();
    }


    private void init() {
        mActivity = this;
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        img_back = (ImageView) this.findViewById(R.id.img_back);
        tv_edit = (TextView) this.findViewById(R.id.tv_edit);
        plv_message = (PullToRefreshListView) mActivity.findViewById(R.id.plv_message);
        tv_delete = (TextView) mActivity.findViewById(R.id.tv_delete);
        tv_no_message_data = (TextView) mActivity.findViewById(R.id.tv_no_message_data);

//        tv_delete.setVisibility(View.GONE);
        dataEntityList = new ArrayList<MessageVipResp.ResultEntity.DataEntity>();
        delete_idList = new ArrayList<Integer>();
        messageVipAdapter = new MessageVipAdapter(dataEntityList);
        plv_message.setAdapter(messageVipAdapter);

//        GetVipMessage(REFRESH);
        plv_message.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetVipMessage(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetVipMessage(MORE);
            }
        });
        img_back.setOnClickListener(this);
        tv_edit.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back://返回
                finish();
                break;
            case R.id.tv_edit://编辑
                if (is_edit == false) {
                    tv_edit.setText("完成");
                    tv_delete.setVisibility(View.VISIBLE);
                    is_edit = true;
                } else {
                    tv_edit.setText("编辑");
                    tv_delete.setVisibility(View.GONE);
                    is_edit = false;
                }
                messageVipAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_delete://删除
//                DeleteVipMessage();
                break;
        }
    }

    private class MessageVipAdapter extends BaseAdapter {
        private List<MessageVipResp.ResultEntity.DataEntity> dataEntityList;
        Typeface type = Typeface.create("", Typeface.BOLD);

        private MessageVipAdapter(List<MessageVipResp.ResultEntity.DataEntity> comment) {
            if (comment == null) {
                comment = new ArrayList<MessageVipResp.ResultEntity.DataEntity>();
            }
            dataEntityList = comment;
        }

        @Override
        public int getCount() {
//            Log.e("url","size=="+dataEntityList.size());
            return dataEntityList.size();
        }

        /**
         * 获得某一位置的数据
         */
        @Override
        public MessageVipResp.ResultEntity.DataEntity getItem(int position) {
            return dataEntityList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.message_system_listitem, null);
                vh = new ViewHolder();
//                vh.img_choose = (ImageView) convertView.findViewById(R.id.img_choose);
                vh.cb_choose = (CheckBox) convertView.findViewById(R.id.cb_choose);
                vh.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
                vh.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
                vh.tv_time = (TextView) convertView.findViewById(R.id.tv_time);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

            if (getItem(position).getStatus() == 0) {//未读消息
//                type = Typeface.create("", Typeface.BOLD);
//                vh.tv_title.setTypeface(type);
                vh.tv_title.setTextColor(getResources().getColor(R.color.e50011));
            } else if (getItem(position).getStatus() == 1) {//已读消息
                vh.tv_title.setTextColor(getResources().getColor(R.color.A666666));
            }

            if (is_edit == true) {
                vh.cb_choose.setVisibility(View.VISIBLE);
                tv_edit.setText("完成");
                tv_delete.setVisibility(View.VISIBLE);
            } else {
                vh.cb_choose.setVisibility(View.GONE);
                tv_edit.setText("编辑");
                tv_delete.setVisibility(View.GONE);
            }

            vh.tv_title.setText(getItem(position).getTitle());
            vh.tv_content.setText(getItem(position).getMessage());
            vh.tv_time.setText(getItem(position).getCreated_at());

//            getItem(position).setIs_check(false);
            final ViewHolder finalVh = vh;
            vh.cb_choose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        getItem(position).setIs_check(true);
                    }
                    if (!isChecked) {
                        getItem(position).setIs_check(false);
                    }
                    messageVipAdapter.notifyDataSetChanged();
                }
            });

            if (getItem(position).is_check() == false) {
                vh.cb_choose.setChecked(false);
            } else if (getItem(position).is_check() == true) {
                vh.cb_choose.setChecked(true);
            }

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("url", "is_edit==" + is_edit);

                    if (is_edit == true) {
                        if (getItem(position).is_check() == false) {
                            finalVh.cb_choose.setChecked(true);
                            getItem(position).setIs_check(true);

                        } else {
                            finalVh.cb_choose.setChecked(false);
                            getItem(position).setIs_check(false);
                        }
                        messageVipAdapter.notifyDataSetChanged();
                    } else {
                        Intent intent = new Intent(mActivity, MessageDetails.class);
                        intent.putExtra("id", getItem(position).getId());
                        intent.putExtra("desc", getItem(position).getMessage());
                        intent.putExtra("time", getItem(position).getCreated_at());
                        intent.putExtra("title", getItem(position).getTitle());
                        intent.putExtra("flag", "messages");
                        startActivityForResult(intent, 1);
                    }
                }
            });

            return convertView;
        }

        private class ViewHolder {
            private ImageView img_choose;
            private CheckBox cb_choose;
            private TextView tv_title;
            public TextView tv_content;
            public TextView tv_time;
        }
    }

    //获取会员消息列表
    private void GetVipMessage(final int type) {
        CustomProgressDialog.createDialog(mActivity).Show();
        MessageVipReq req = new MessageVipReq();

        if (myApplication.getDataEntity() == null) {
            return;
        } else {
            req.setUuid(myApplication.getDataEntity().getUuid());
        }

        if (myApplication.getVip_time() == null) {
            req.setTime("1");
        } else {
            req.setTime(myApplication.getVip_time());
        }

        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = dataEntityList.size() / 10 + 1;
        }
        req.setPage(page + "");
        req.setType("0");
        req.setPage_size("10");

        RequestParams params = new RequestParams();

        if (sharedPreferencesUtil.getAccessToken() != null) {
            params.put("token", sharedPreferencesUtil.getAccessToken());
        }

        params.put("secret", req.getSecret());

        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("url", "vip_meesage_json==" + response);
                CustomProgressDialog.Dismiss();
                plv_message.onRefreshComplete();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    MessageVipResp resp = GsonImpl.get().toObject(response.toString(), MessageVipResp.class);
                    myApplication.setMessage_time(System.currentTimeMillis() + "");
                    if (type == LOAD || type == REFRESH) {
                        dataEntityList.clear();
                        dataEntityList.addAll(resp.getResult().getData());
                    } else {
                        dataEntityList.addAll(resp.getResult().getData());
                    }
                    if (dataEntityList.size() % 10 > 0) {
                        plv_message.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        plv_message.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    messageVipAdapter.notifyDataSetChanged();
                    plv_message.onRefreshComplete();
                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 1);
                    Log.e("url", "errmsg==" + errmsg);
                } else {
                    tv_no_message_data.setVisibility(View.VISIBLE);
                    CommonUtil.showToast(mActivity, errmsg);
                    messageVipAdapter.notifyDataSetChanged();
                    plv_message.onRefreshComplete();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

//    //删除会员消息
//    private void DeleteVipMessage() {
//        CustomProgressDialog.createDialog(mActivity).Show();
//        DeleteVipMessageReq req = new DeleteVipMessageReq();
//
//        for (MessageVipResp.ResultEntity.DataEntity dataEntity : dataEntityList) {
//            if (dataEntity.getIs_check() == true) {
//                delete_idList.add(dataEntity.getId());
//            }
//        }
//
//        StringBuffer buffer = new StringBuffer();
//        for (int i = 0; i < delete_idList.size(); i++) {
//            if (i == delete_idList.size() - 1) {
//                buffer.append(delete_idList.get(i));
//            } else {
//                buffer.append(delete_idList.get(i) + ",");
//            }
//        }
//
//        Log.e("url", "delete_idList==" + delete_idList);
//        Log.e("url", "delete_idList.size==" + delete_idList.size());
//
//        if (delete_idList.size() == 0) {
//            CustomProgressDialog.Dismiss();
//            delete_idList.clear();
//            CommonUtil.showToast(mActivity, "请至少选择一条消息");
//            return;
//        }
//
//        req.setId(buffer.toString());
//        req.setType("message");
//        req.setAccess_token(sharedPreferencesUtil.getAccessToken());
//        String url = Const.COMMON_ADDRESS + req.urlString();
//        RequestParams params = new RequestParams();
//        params.put("id", req.getId());
//        params.put("type", req.getType());
//        params.put("access_token", sharedPreferencesUtil.getAccessToken());
//        params.put("secret", req.getString());
//        Log.e("url", "params==" + params);
//        AsyncHttpClient client = new AsyncHttpClient();
//        client.delete(url, params, new JsonHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//                super.onSuccess(statusCode, headers, response);
//                CustomProgressDialog.Dismiss();
//                String errno = response.optString("errno");
//                String errmsg = response.optString("errmsg");
//                if (errno.equals("000")) {
//                    GetVipMessage(REFRESH);
//                    messageVipAdapter.notifyDataSetChanged();
//                    tv_edit.setText("编辑");
//                    tv_delete.setVisibility(View.GONE);
//                    CommonUtil.showToast(mActivity, errmsg);
//                    delete_idList.clear();
//                    is_edit = false;
//                } else if (errno.equals("999")) {
//                    CommonUtil.showToast(mActivity, errmsg);
//                    Intent intent = new Intent(mActivity, LoginActivity.class);
//                    startActivityForResult(intent, 1);
//                    Log.e("url", "errmsg==" + errmsg);
//                } else {
//                    CommonUtil.showToast(mActivity, errmsg);
//                }
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                super.onFailure(statusCode, headers, responseString, throwable);
//                CustomProgressDialog.Dismiss();
//                CommonUtil.showToast(mActivity, "网络连接失败");
//            }
//        });
//    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("url", "messageVip_onResume");
        if (login_flag == 0) {
            GetVipMessage(REFRESH);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("url", "messageVip_onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("url", "messageVip_onStop");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    GetVipMessage(REFRESH);
                }
                break;
        }
    }

}
